<?php
/**
 * Created by PhpStorm.
 * User: huliren<huliren0516@163.com>
 * Date: 2017/10/17
 * Time: 17:46
 */
define('SITE_AUTH', 'mobile-firmware-version');
require('../../../common.inc.php');

use lib\core\AdminAction;
use Mobile\FirmwareVersion as Model;
use Common\Upload;
use Common\ResourcePathManager;

class firmwareVersion extends AdminAction
{
    private $list_url = 'data/modules/mobile/firmwareVersion.php';

    public function doDefault()
    {
        $smarty = $this->app->page();

        $where = ['Id >' => 0];

        $page = $_GET['page'] < 1 ? 1 : (int)$_GET['page'];
        $limit = 5;
        $offset = ($page - 1) * $limit;

        $data = Model::getList($where, $offset, $limit);
        $count = $data['count'];

        if ($count > 0) {
            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('page_info', $page_info);
            $smarty->value('pagination', $pagination);
            $smarty->value('list', $data['data']);
        }

        $smarty->output();
    }

    public function doEdit()
    {
        $smarty = $this->app->page();
        $smarty->output('mobile/firmwareVersion_edit.tpl');
    }

    public function doUpdata()
    {
        $firmware = $_FILES['firmware'];
        $version = trim($_POST['version']);
        $md5 = trim($_POST['MD5']);
        $name = trim($_POST['name']);

        $fileUrl = '';
        if (isset($firmware['name']) && $firmware['error'] == 0 && $firmware['size'] > 0) {
            $fileUrl = Upload::uploadFile($firmware, ResourcePathManager::getFirmwareSavePath());
        }

        $data = [
            Model::FIELD_VERSIONCODE => $version,
            Model::FIELD_NAME=>$name,
            Model::FIELD_MD5=>$md5,
            Model::FIELD_DOWURL => $fileUrl
        ];

        $res = Model::add($data);

        if ($res) {
            HDshowMsg('保存成功', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('操作失败', ['type' => 'error']);
        }

    }

    public function doDelete()
    {
        $id = $_GET['id'];
        $res = Model::delete($id);

        if ($res) {
            HDshowMsg('保存成功', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('操作失败', ['type' => 'error']);
        }
    }
}

$app->run();